#!/usr/bin/env python3
"""
Example Usage of Documentation Generation Utilities

This script demonstrates how to use the documentation generation utilities
both as standalone tools and integrated with the fortran_commentator package.
"""

import sys
from pathlib import Path
import tempfile
import os

# Import the utilities
from documentation_generator import DocumentationManager
from generate_gsi_docs import discover_gsi_classification_files


def create_sample_fortran_file(filepath: Path) -> None:
    """Create a sample Fortran file with structured comments for testing."""
    content = '''!> @brief Calculate the distance between two points in 2D space
!> @details This function computes the Euclidean distance between two points
!> in a 2D coordinate system using the standard distance formula.
!> @param[in] x1 X-coordinate of first point [real]
!> @param[in] y1 Y-coordinate of first point [real] 
!> @param[in] x2 X-coordinate of second point [real]
!> @param[in] y2 Y-coordinate of second point [real]
!> @return Distance between the two points [real]
!> @usage
!> real :: dist
!> dist = calculate_distance(0.0, 0.0, 3.0, 4.0)
!> @algorithm
!> 1. Calculate differences: dx = x2 - x1, dy = y2 - y1
!> 2. Apply distance formula: sqrt(dx^2 + dy^2)
!> @see point_distance_3d, vector_magnitude
!> @author Example Author
!> @date 2025-01-12
real function calculate_distance(x1, y1, x2, y2)
    implicit none
    real, intent(in) :: x1, y1, x2, y2
    real :: dx, dy
    
    dx = x2 - x1
    dy = y2 - y1
    calculate_distance = sqrt(dx*dx + dy*dy)
end function calculate_distance

!> @brief Initialize coordinate system parameters
!> @details Sets up the coordinate system with origin and scaling factors
!> @param[out] origin_x X-coordinate of origin [real]
!> @param[out] origin_y Y-coordinate of origin [real]
!> @param[in] scale_factor Scaling factor for coordinates [real]
!> @usage
!> call setup_coordinates(ox, oy, 1.0)
!> @see reset_coordinates
subroutine setup_coordinates(origin_x, origin_y, scale_factor)
    implicit none
    real, intent(out) :: origin_x, origin_y
    real, intent(in) :: scale_factor
    
    origin_x = 0.0
    origin_y = 0.0
    ! Apply scaling if needed
    if (scale_factor /= 1.0) then
        origin_x = origin_x * scale_factor
        origin_y = origin_y * scale_factor
    end if
end subroutine setup_coordinates
'''
    
    with open(filepath, 'w') as f:
        f.write(content)


def example_documentation_generation():
    """Example of using the documentation generator."""
    print("=== Documentation Generation Example ===")
    
    # Create temporary directory for the example
    with tempfile.TemporaryDirectory() as temp_dir:
        temp_path = Path(temp_dir)
        
        # Create sample source files
        src_dir = temp_path / 'src'
        src_dir.mkdir()
        
        sample_file = src_dir / 'geometry.f90'
        create_sample_fortran_file(sample_file)
        
        # Create output directory
        output_dir = temp_path / 'docs'
        
        print(f"Created sample file: {sample_file}")
        print(f"Output directory: {output_dir}")
        
        # Initialize documentation manager
        doc_manager = DocumentationManager("Example Fortran Project")
        
        # Generate documentation
        try:
            results = doc_manager.generate_documentation(
                source_paths=[src_dir],
                output_dir=output_dir,
                formats=['html'],
                analyze_relationships=True
            )
            
            print(f"✅ Documentation generated successfully!")
            print(f"📄 Processed {results['parsed_files']} files")
            print(f"📁 Output: {output_dir}")
            
            # List generated files
            if output_dir.exists():
                html_dir = output_dir / 'html'
                if html_dir.exists():
                    html_files = list(html_dir.glob('*.html'))
                    print(f"📋 Generated {len(html_files)} HTML files:")
                    for html_file in html_files:
                        print(f"   - {html_file.name}")
            
        except Exception as e:
            print(f"❌ Documentation generation failed: {e}")


def example_gsi_classification():
    """Example of working with GSI classification structure."""
    print("\n=== GSI Classification Example ===")
    
    # Look for GSI classification directory in the project
    current_dir = Path(__file__).parent
    project_root = current_dir.parent.parent.parent.parent.parent
    gsi_classification_dir = project_root / 'gsi_classification'
    
    if gsi_classification_dir.exists():
        print(f"Found GSI classification directory: {gsi_classification_dir}")
        
        # Discover files by classification
        classifications = discover_gsi_classification_files(gsi_classification_dir)
        
        print("\nGSI Files by Classification:")
        total_files = 0
        for class_name, files in classifications.items():
            print(f"  {class_name}: {len(files)} files")
            if files:
                # Show first few files as examples
                for i, file_path in enumerate(files[:3]):
                    print(f"    - {file_path.name}")
                if len(files) > 3:
                    print(f"    ... and {len(files) - 3} more files")
            total_files += len(files)
        
        print(f"  Total: {total_files} files")
        
        if total_files > 0:
            print(f"\n💡 To generate GSI documentation, run:")
            print(f"python generate_gsi_docs.py \\")
            print(f"  --gsi-classification {gsi_classification_dir} \\")
            print(f"  --output-dir ./gsi_documentation \\")
            print(f"  --formats html \\")
            print(f"  --separate-classifications")
    else:
        print("GSI classification directory not found in project structure")
        print(f"Expected location: {gsi_classification_dir}")


def example_integration_with_commentator():
    """Example of integrating with the main fortran_commentator system."""
    print("\n=== Integration with Fortran Commentator ===")
    
    try:
        # Try to import from the main package
        sys.path.insert(0, str(Path(__file__).parent.parent.parent))
        from fortran_commentator import CodeCommentarySystem, DEFAULT_CONFIG
        
        print("✅ Successfully imported from fortran_commentator package")
        print(f"📋 Default config keys: {list(DEFAULT_CONFIG.keys())}")
        
        print("\n💡 Integration workflow:")
        print("1. Use CodeCommentarySystem to add structured comments to Fortran code")
        print("2. Use DocumentationManager to generate professional documentation")
        print("3. Combine both for end-to-end documentation pipeline")
        
    except ImportError as e:
        print(f"❌ Could not import fortran_commentator: {e}")
        print("This is normal when running as standalone utility")


def main():
    """Run all examples."""
    print("Fortran Code Commentator - Utilities Examples")
    print("=" * 50)
    
    # Run examples
    example_documentation_generation()
    example_gsi_classification()
    example_integration_with_commentator()
    
    print("\n" + "=" * 50)
    print("Examples completed!")
    print("\nFor more information, see:")
    print("- README.md in this directory")
    print("- Main fortran_commentator documentation")
    print("- Run utilities with --help for command-line options")


if __name__ == '__main__':
    main()